# Copyright 2021 Josh Newans
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import rclpy
from rclpy.node import Node

from std_msgs.msg import Header
from geometry_msgs.msg import Twist
from geometry_msgs.msg import TwistWithCovariance
from geometry_msgs.msg import Pose
from geometry_msgs.msg import PoseWithCovariance

covariance = [
    0.1, 0.0, 0.0, 0.0, 0.0, 0.0,  # x 坐标的方差及其与其他变量的协方差
    0.0, 0.2, 0.0, 0.0, 0.0, 0.0,  # y 坐标的方差及其与其他变量的协方差
    0.0, 0.0, 0.3, 0.0, 0.0, 0.0,  # z 坐标的方差及其与其他变量的协方差
    0.0, 0.0, 0.0, 0.4, 0.0, 0.0,  # 滚转角的方差
    0.0, 0.0, 0.0, 0.0, 0.5, 0.0,  # 俯仰角的方差
    0.0, 0.0, 0.0, 0.0, 0.0, 0.6   # 偏航角的方差
]

class TwistStamper(Node):

    def __init__(self):
        super().__init__('pose_covariance')#节点名称

        self.publisher_ = self.create_publisher(PoseWithCovariance, 'posewithcovariance', 10)
        self.publisher1_ = self.create_publisher(TwistWithCovariance, 'twistwithcovariance', 10)

        self.subscription = self.create_subscription(
            Pose,
            'pose',
            self.listener_callback,
            10)
        self.subscription = self.create_subscription(
            Twist,
            'twist',
            self.listener_callback1,
            10)
        self.subscription  # prevent unused variable warning
        self.get_logger().info("等待pose and twist...") 

    def listener_callback(self, inMsg):
        outMsg = PoseWithCovariance()
        outMsg.pose = inMsg
        outMsg.covariance = covariance

        self.publisher_.publish(outMsg)
        # self.get_logger().info('X: "%f"' % outMsg.twist.linear.x)
    
    def listener_callback1(self, inMsg1):
        outMsg1 = TwistWithCovariance()
        outMsg1.twist = inMsg1
        outMsg1.covariance = covariance

        self.publisher1_.publish(outMsg1)
        # self.get_logger().info('X: "%f"' % outMsg.twist.linear.x)

def main(args=None):
    rclpy.init(args=args)

    twist_stamper = TwistStamper()
    rclpy.spin(twist_stamper)

    twist_stamper.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()
